import React, { useState, useContext } from "react";
import {
  View,
  TouchableOpacity,
  StyleSheet,
  Dimensions,
  Text,
  Button,
  Platform,
  TextInput,
  ScrollView,
  Alert,
} from "react-native";

import { useDispatch } from "react-redux";
import { register } from "../../store/actions";

import { Feather } from "@expo/vector-icons";
import { FontAwesome } from "@expo/vector-icons";
import { FontAwesome5 } from "@expo/vector-icons";
import { MaterialIcons } from "@expo/vector-icons";
import * as Animatable from "react-native-animatable";
import { AntDesign } from "@expo/vector-icons";
import LoadingBar from "../../components/InterView/LoadingBar";

const SignUpScreen = ({ navigation }) => {
  const dispatch = useDispatch();

  const [error, setError] = useState(false);
  // const roles = ["调研员", "管理员", "审核员"]; //0 1 2
  const roles = ["调研员", "管理员"]; //0 1 2
  const [selected, setSelected] = useState(0);
  const [isLoading, setIsLoading] = useState(false);

  const [data, setData] = useState({
    account: "",
    password: "",
    confirm_password: "",
    group: "", //第几组
    role: selected, //角色
    name: "", //姓名
    check_textInputChange: false,
    check_groupInputChange: false,
    check_nameInputChange: false,
    secureTextEntry: true,
    confirmSecureTextEntry: true,
  });
  const textInputChange = (val) => {
    if (val.length != 0) {
      setData({ ...data, account: val, check_textInputChange: true });
    } else {
      setData({ ...data, account: val, check_textInputChange: false });
    }
  };

  const groupInputChange = (val) => {
    if (val.length != 0) {
      setData({ ...data, group: val, check_groupInputChange: true });
    } else {
      setData({ ...data, group: val, check_groupInputChange: false });
    }
  };
  const nameInputChange = (val) => {
    if (val.length != 0) {
      setData({ ...data, name: val, check_nameInputChange: true });
    } else {
      setData({ ...data, name: val, check_nameInputChange: false });
    }
  };
  const handlePasswordChange = (val) => {
    let iserror = false;
    setData({ ...data, password: val });
    if (val !== data.confirm_password) {
      iserror = true;
    }
    setError(iserror);
  };
  const handleConfirmPasswordChange = (val) => {
    let iserror = false;
    setData({ ...data, confirm_password: val });
    if (val !== data.password) {
      iserror = true;
    }
    setError(iserror);
  };

  const updateSecureTextEntry = (val) => {
    setData({ ...data, secureTextEntry: !data.secureTextEntry });
  };
  const updateConfirmSecureTextEntry = (val) => {
    setData({ ...data, confirmSecureTextEntry: !data.confirmSecureTextEntry });
  };

  const confirm = () => {
    Alert.alert("提示", "确定提交吗？", [
      {
        text: "取消",
      },
      {
        text: "确定",
        onPress: () => {
          if (
            data.account.length == 0 ||
            data.password.length == 0 ||
            data.name.length == 0 ||
            data.confirm_password == 0
          ) {
            Alert.alert("提示", "输入内容不能为空", [{ text: "确定" }]);
            return;
          }
          if (selected !== 2 && data.group.length === 0) {
            Alert.alert("提示", "输入内容不能为空", [{ text: "确定" }]);
            return;
          }
          if (data.password !== data.confirm_password) {
            Alert.alert("提示", "两次输入密码不一致", [{ text: "确定" }]);
            return;
          }
          let role;
          if (selected == 0) {
            role = "user";
          } else if (selected == 1) {
            role = "admin";
          } else {
            role = "auditor";
          }

          let item = {
            account: data.account,
            name: data.name,
            password: data.password,
            group: data.group,
            role: role,
          };

          dispatch(
            register(
              item,
              () => navigation.navigate("SignInScreen"),
              setIsLoading
            )
          );
        },
      },
    ]);
  };

  return (
    <View style={styles.container}>
      <LoadingBar visible={isLoading} />
      <View style={styles.header}>
        <Text style={styles.text_header}>Register Now!</Text>
      </View>

      <Animatable.View style={styles.footer} animation="fadeInUpBig">
        <ScrollView style={{ paddingHorizontal: 20, flex: 1 }}>
          <Text style={[styles.text_footer, { marginTop: 20 }]}>账号</Text>
          <View style={styles.action}>
            <FontAwesome5 name="user-alt" size={16} color="#05375a" />

            <TextInput
              placeholder="请输入账号"
              style={styles.textInput}
              autoCapitalize="none"
              onChangeText={(val) => textInputChange(val)}
            />
            {data.check_textInputChange ? (
              <Animatable.View animation="bounceIn">
                <Feather name="check-circle" color="green" size={18} />
              </Animatable.View>
            ) : null}
          </View>

          <Text style={[styles.text_footer, { marginTop: 10 }]}>姓名</Text>
          <View style={styles.action}>
            <AntDesign name="carryout" size={18} color="#05375a" />
            <TextInput
              placeholder="请输入真实姓名"
              style={styles.textInput}
              autoCapitalize="none"
              onChangeText={(val) => nameInputChange(val)}
            />
            {data.check_nameInputChange ? (
              <Animatable.View animation="bounceIn">
                <Feather name="check-circle" color="green" size={18} />
              </Animatable.View>
            ) : null}
          </View>
          <Text style={[styles.text_footer, { marginTop: 10 }]}>角色</Text>
          <View
            style={{
              flexDirection: "row",
              justifyContent: "space-around",
              marginTop: 10,
            }}
          >
            {roles.map((item, index) => {
              return (
                <TouchableOpacity
                  key={index}
                  onPress={() => setSelected(index)}
                >
                  <Text
                    style={index === selected ? styles.selectedTag : styles.tag}
                  >
                    {item}
                  </Text>
                </TouchableOpacity>
              );
            })}
          </View>
          {selected !== 2 && (
            <>
              <Text style={[styles.text_footer, { marginTop: 10 }]}>组号</Text>
              <View style={styles.action}>
                <MaterialIcons name="group" size={20} color="#05375a" />
                <TextInput
                  placeholder="请输入组号"
                  style={styles.textInput}
                  autoCapitalize="none"
                  onChangeText={(val) => groupInputChange(val)}
                />
                {data.check_groupInputChange ? (
                  <Animatable.View animation="bounceIn">
                    <Feather name="check-circle" color="green" size={18} />
                  </Animatable.View>
                ) : null}
              </View>
            </>
          )}

          <Text style={[styles.text_footer, { marginTop: 10 }]}>密码</Text>
          <View style={styles.action}>
            <FontAwesome name="lock" color="#05375a" size={20} />
            <TextInput
              placeholder="请输入密码"
              style={styles.textInput}
              secureTextEntry={data.secureTextEntry ? true : false}
              autoCapitalize="none"
              onChangeText={(val) => handlePasswordChange(val)}
            />
            <TouchableOpacity onPress={updateSecureTextEntry}>
              {data.secureTextEntry ? (
                <Feather name="eye-off" color="gray" size={20} />
              ) : (
                <Feather name="eye" color="gray" size={20} />
              )}
            </TouchableOpacity>
          </View>
          <Text style={[styles.text_footer, { marginTop: 10 }]}>确认密码</Text>
          <View style={styles.action}>
            <FontAwesome name="lock" color="#05375a" size={20} />
            <TextInput
              placeholder="请确认你的密码"
              style={styles.textInput}
              secureTextEntry={data.confirmSecureTextEntry ? true : false}
              autoCapitalize="none"
              onChangeText={(val) => handleConfirmPasswordChange(val)}
            />
            <TouchableOpacity onPress={updateConfirmSecureTextEntry}>
              {data.confirmSecureTextEntry ? (
                <Feather name="eye-off" color="gray" size={20} />
              ) : (
                <Feather name="eye" color="gray" size={20} />
              )}
            </TouchableOpacity>
          </View>
          {error ? (
            <Text style={styles.errorMsg}>两次输入密码不一致</Text>
          ) : null}
          <View style={styles.button}>
            <TouchableOpacity style={styles.signUp} onPress={() => confirm()}>
              <Text style={styles.textSignUp}>注 册</Text>
            </TouchableOpacity>
          </View>
        </ScrollView>
      </Animatable.View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#780808",
  },
  header: {
    flex: 1,
    justifyContent: "flex-end",
    paddingHorizontal: 20,
    paddingBottom: 50,
  },
  footer: {
    flex: 3.5,
    backgroundColor: "#fff",
    borderTopLeftRadius: 30,
    borderTopRightRadius: 30,
    // paddingHorizontal: 20,
    // paddingVertical: 30,
  },
  text_header: {
    color: "#fff",
    fontWeight: "bold",
    fontSize: 30,
  },
  text_footer: {
    color: "#05375a",
    fontSize: 16,
  },
  action: {
    flexDirection: "row",
    marginTop: 10,
    borderBottomWidth: 1,
    borderBottomColor: "#f2f2f2",
    paddingBottom: 5,
  },
  actionError: {
    flexDirection: "row",
    marginTop: 10,
    borderBottomWidth: 1,
    borderBottomColor: "#FF0000",
    paddingBottom: 5,
  },
  textInput: {
    flex: 1,
    marginTop: Platform.OS === "ios" ? 0 : -12,
    paddingLeft: 10,
    color: "#05375a",
  },
  errorMsg: {
    marginTop: 10,
    color: "#FF0000",
    fontSize: 14,
  },
  button: {
    alignItems: "center",
    marginTop: 25,
    marginBottom: 20,
  },
  signUp: {
    backgroundColor: "#A80108",
    width: "100%",
    height: 50,
    justifyContent: "center",
    alignItems: "center",
    borderRadius: 10,
  },
  signIn: {
    borderColor: "#009387",
    borderWidth: 1,
    marginTop: 15,
    width: "100%",
    height: 50,
    justifyContent: "center",
    alignItems: "center",
    borderRadius: 10,
  },
  textSignUp: {
    fontSize: 18,
    fontWeight: "bold",
    color: "#fff",
  },
  textSignIn: {
    fontSize: 18,
    fontWeight: "bold",
    color: "#05375a",
  },
  selectedTag: {
    borderWidth: 1,
    borderColor: "#A80108",
    padding: 1,
    paddingLeft: 10,
    paddingRight: 10,
    borderRadius: 2,
    color: "#A80108",
  },
  tag: {
    borderWidth: 1,
    borderColor: "#d1d1d6",
    padding: 1,
    paddingLeft: 10,
    paddingRight: 10,
    borderRadius: 10,
    color: "#d1d1d6",
    fontSize: 14,
  },
});

export default SignUpScreen;
